const prisma = require('../utils/prisma');
const { success, error } = require('../utils/response');

/**
 * 获取菜品列表
 * @route GET /api/dishes
 */
const getDishes = async (req, res) => {
  try {
    const { categoryId } = req.query;
    
    // 构建查询条件
    const where = {};
    if (categoryId) {
      where.categoryId = categoryId;
    }
    
    const dishes = await prisma.dish.findMany({
      where,
      include: {
        category: true
      },
      orderBy: {
        createdAt: 'desc'
      }
    });
    
    return success(res, dishes);
  } catch (err) {
    console.error('Get dishes error:', err);
    return error(res, 'Failed to get dishes', 500);
  }
};

/**
 * 获取菜品分类
 * @route GET /api/dishes/categories
 */
const getCategories = async (req, res) => {
  try {
    const categories = await prisma.category.findMany({
      orderBy: {
        createdAt: 'asc'
      }
    });
    
    return success(res, categories);
  } catch (err) {
    console.error('Get categories error:', err);
    return error(res, 'Failed to get categories', 500);
  }
};

/**
 * 获取指定菜品
 * @route GET /api/dishes/:id
 */
const getDishById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const dish = await prisma.dish.findUnique({
      where: { id },
      include: {
        category: true
      }
    });
    
    if (!dish) {
      return error(res, 'Dish not found', 404);
    }
    
    return success(res, dish);
  } catch (err) {
    console.error('Get dish error:', err);
    return error(res, 'Failed to get dish', 500);
  }
};

/**
 * 创建菜品
 * @route POST /api/dishes
 */
const createDish = async (req, res) => {
  try {
    const { name, description, image, categoryId } = req.body;
    
    if (!name || !categoryId) {
      return error(res, 'Name and category are required', 400);
    }
    
    // 检查分类是否存在
    const category = await prisma.category.findUnique({
      where: { id: categoryId }
    });
    
    if (!category) {
      return error(res, 'Category not found', 404);
    }
    
    // 创建菜品
    const dish = await prisma.dish.create({
      data: {
        name,
        description,
        image,
        categoryId
      },
      include: {
        category: true
      }
    });
    
    return success(res, dish, 'Dish created successfully', 201);
  } catch (err) {
    console.error('Create dish error:', err);
    return error(res, 'Failed to create dish', 500);
  }
};

/**
 * 更新菜品
 * @route PUT /api/dishes/:id
 */
const updateDish = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, description, image, categoryId } = req.body;
    
    // 检查菜品是否存在
    const existingDish = await prisma.dish.findUnique({
      where: { id }
    });
    
    if (!existingDish) {
      return error(res, 'Dish not found', 404);
    }
    
    // 如果更新分类，检查分类是否存在
    if (categoryId) {
      const category = await prisma.category.findUnique({
        where: { id: categoryId }
      });
      
      if (!category) {
        return error(res, 'Category not found', 404);
      }
    }
    
    // 更新菜品
    const updateData = {};
    
    if (name) updateData.name = name;
    if (description !== undefined) updateData.description = description;
    if (image !== undefined) updateData.image = image;
    if (categoryId) updateData.categoryId = categoryId;
    
    const updatedDish = await prisma.dish.update({
      where: { id },
      data: updateData,
      include: {
        category: true
      }
    });
    
    return success(res, updatedDish, 'Dish updated successfully');
  } catch (err) {
    console.error('Update dish error:', err);
    return error(res, 'Failed to update dish', 500);
  }
};

/**
 * 删除菜品
 * @route DELETE /api/dishes/:id
 */
const deleteDish = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查菜品是否存在
    const existingDish = await prisma.dish.findUnique({
      where: { id }
    });
    
    if (!existingDish) {
      return error(res, 'Dish not found', 404);
    }
    
    // 检查菜品是否被菜单引用
    const menuItems = await prisma.menuItem.findMany({
      where: { dishId: id }
    });
    
    if (menuItems.length > 0) {
      return error(res, 'Cannot delete dish that is referenced in menus', 400);
    }
    
    // 删除菜品
    await prisma.dish.delete({
      where: { id }
    });
    
    return success(res, null, 'Dish deleted successfully');
  } catch (err) {
    console.error('Delete dish error:', err);
    return error(res, 'Failed to delete dish', 500);
  }
};

/**
 * 创建菜品分类
 * @route POST /api/dishes/categories
 */
const createCategory = async (req, res) => {
  try {
    const { name } = req.body;
    
    if (!name) {
      return error(res, 'Name is required', 400);
    }
    
    // 创建分类
    const category = await prisma.category.create({
      data: { name }
    });
    
    return success(res, category, 'Category created successfully', 201);
  } catch (err) {
    console.error('Create category error:', err);
    return error(res, 'Failed to create category', 500);
  }
};

/**
 * 更新菜品分类
 * @route PUT /api/dishes/categories/:id
 */
const updateCategory = async (req, res) => {
  try {
    const { id } = req.params;
    const { name } = req.body;
    
    if (!name) {
      return error(res, 'Name is required', 400);
    }
    
    // 检查分类是否存在
    const existingCategory = await prisma.category.findUnique({
      where: { id }
    });
    
    if (!existingCategory) {
      return error(res, 'Category not found', 404);
    }
    
    // 更新分类
    const updatedCategory = await prisma.category.update({
      where: { id },
      data: { name }
    });
    
    return success(res, updatedCategory, 'Category updated successfully');
  } catch (err) {
    console.error('Update category error:', err);
    return error(res, 'Failed to update category', 500);
  }
};

/**
 * 删除菜品分类
 * @route DELETE /api/dishes/categories/:id
 */
const deleteCategory = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查分类是否存在
    const existingCategory = await prisma.category.findUnique({
      where: { id }
    });
    
    if (!existingCategory) {
      return error(res, 'Category not found', 404);
    }
    
    // 检查分类是否被菜品引用
    const dishes = await prisma.dish.findMany({
      where: { categoryId: id }
    });
    
    if (dishes.length > 0) {
      return error(res, 'Cannot delete category that contains dishes', 400);
    }
    
    // 删除分类
    await prisma.category.delete({
      where: { id }
    });
    
    return success(res, null, 'Category deleted successfully');
  } catch (err) {
    console.error('Delete category error:', err);
    return error(res, 'Failed to delete category', 500);
  }
};

module.exports = {
  getDishes,
  getCategories,
  getDishById,
  createDish,
  updateDish,
  deleteDish,
  createCategory,
  updateCategory,
  deleteCategory
};
